package com.moli.iov.sys.remote.impl;

import com.moli.iov.exception.BusinessException;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.enums.RoleStatusEnum;
import com.moli.iov.sys.enums.UserStatusEnum;
import com.moli.iov.sys.enums.UserTypeEnum;
import com.moli.iov.sys.model.dto.req.PwdDto;
import com.moli.iov.sys.model.dto.req.RoleDto;
import com.moli.iov.sys.model.dto.req.UserDto;
import com.moli.iov.sys.model.dto.req.UserThirdDto;
import com.moli.iov.sys.model.dto.res.UserRoleDto;
import com.moli.iov.sys.model.po.Company;
import com.moli.iov.sys.model.po.Role;
import com.moli.iov.sys.model.po.User;
import com.moli.iov.sys.model.po.UserRole;
import com.moli.iov.sys.remote.ICompanyRemoteService;
import com.moli.iov.sys.remote.IUserThirdRemoteService;
import com.moli.iov.sys.service.IRoleService;
import com.moli.iov.sys.service.IUserRoleService;
import com.moli.iov.sys.service.IUserService;
import com.moli.iov.sys.utils.PwdUtil;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.ValidationUtils;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 用户业务  第三方 调用
 * </p>
 *
 * @author zql
 * @since 2019/9/21 10:34
 */
@Slf4j
@Service(group = "${service.group}")
public class UserThirdRemoteServiceImpl implements IUserThirdRemoteService {

  @Autowired
  private ICompanyRemoteService companyRemoteService;

  @Autowired
  private IUserService userService;

  @Autowired
  private IRoleService roleService;

  @Autowired
  private IUserRoleService userRoleService;

  /**
   * 分页查询用户列表
   */
  @Override
  public RestResponse<PageExtend<User>> listUserOfPage(UserThirdDto userThirdDto) {

    listUserOfPageValid(userThirdDto);

    UserDto userDto = new UserDto();
    CommonUtils.copyProperties(userThirdDto, userDto);
    return RestResponse.success(userService.listUserOfPage(userDto));
  }

  /**
   * 查询参数校验
   */
  private void listUserOfPageValid(UserThirdDto userThirdDto) {

    ValidationUtils.restResponseValidate(userThirdDto, UserThirdDto.Query.class);
    companyRemoteService.companyValid(userThirdDto.getCompanyId());
  }

  /**
   * 添加用户
   */
  @Override
  public RestResponse saveUser(UserThirdDto userThirdDto) {

    saveUserValid(userThirdDto);

    User user = userService.saveUser(assembleUser(userThirdDto));
    if (user.getUserId() == null) {
      return RestResponse.failure("添加用户失败");
    }

    if(userThirdDto.getRoleId() != null){
      boolean isT = userRoleService
          .setUserRole(new UserRole(userThirdDto.getRoleId(), user.getUserId()));
      if (!isT) {
        throw new BusinessException("添加用户失败");
      }
    }


    return RestResponse.success();
  }

  /**
   * 组装用户实体
   */
  private User assembleUser(UserThirdDto userThirdDto) {
    User user = new User();
    CommonUtils.copyProperties(userThirdDto, user);
    user.setAccount(user.getEmail());
    user.setUserType(UserTypeEnum.COMPANY.getFlag());

    return user;
  }

  /**
   * 添加用户参数校验
   */
  private UserThirdDto saveUserValid(UserThirdDto userThirdDto) {

    ValidationUtils.restResponseValidate(userThirdDto, UserThirdDto.Save.class);

    UserDto userDto = new UserDto();
    userDto.setEmail(userThirdDto.getEmail());
    List<User> users = userService.listUsers(userDto);
    if (users != null && !users.isEmpty()) {
      throw new BusinessException("邮箱已经存在");
    }

    userDto = new UserDto();
    userDto.setUserPhone(userThirdDto.getUserPhone());
    users = userService.listUsers(userDto);
    if (users != null && !users.isEmpty()) {
      throw new BusinessException("手机号已经存在");
    }

    if(userThirdDto.getRoleId() != null){
      roleValid(userThirdDto.getRoleId());
    }

    Company company = companyRemoteService.companyValid(userThirdDto.getCompanyId());
    userThirdDto.setCompanyName(company.getCompanyName());

    return userThirdDto;
  }

  /**
   * 校验角色
   */
  private Role roleValid(Long roleId) {
    Role roleByRoleId = roleService.getRoleByRoleId(roleId);
    if (roleByRoleId == null) {
      throw new BusinessException("角色id不存在");
    }

    if (RoleStatusEnum.DISABLED.getFlag() == roleByRoleId.getStatus()) {
      throw new BusinessException("角色已停用");
    }

    return roleByRoleId;
  }

  /**
   * 修改用户
   */
  @Override
  public RestResponse updateUser(UserThirdDto userThirdDto) {

    updateUserValid(userThirdDto);

    User user = new User();
    CommonUtils.copyProperties(userThirdDto, user);
    boolean isT = userService.updateUser(user);
    if (!isT) {
      return RestResponse.failure("修改用户失败");
    }

    if(userThirdDto.getRoleId() == null){
      UserRole userRole = new UserRole();
      userRole.setUserId(userThirdDto.getUserId());
      userRoleService.deleteUserRole(userRole);
    }else{
      isT =
          userRoleService.setUserRole(new UserRole(userThirdDto.getRoleId(), userThirdDto.getUserId()));
    }

    if (!isT) {
      throw new BusinessException("修改用户失败");
    }
    return RestResponse.success();
  }

  /**
   * 修改用户参数校验
   */
  private UserThirdDto updateUserValid(UserThirdDto userThirdDto) {
    ValidationUtils.restResponseValidate(userThirdDto, UserThirdDto.Update.class);

    companyRemoteService.companyValid(userThirdDto.getCompanyId());

    User user = userService.getUserByAccount(userThirdDto.getAccount());
    if (user == null) {
      throw new BusinessException("用户账号不存在");
    }

    if(userThirdDto.getRoleId() != null){
      roleValid(userThirdDto.getRoleId());
    }

    if (!user.getCompanyId().equals(userThirdDto.getCompanyId())) {
      throw new BusinessException("用户与企业不匹配");
    }

    userThirdDto.setUserId(user.getUserId());

    return userThirdDto;
  }

  /**
   * 重置密码
   */
  @Override
  public RestResponse resetPwd(UserThirdDto userThirdDto) {

    User user = resetPwdValid(userThirdDto);

    PwdDto pwdDto = PwdUtil.createPassword(userThirdDto.getEmail());
    user.setPassword(pwdDto.getEnPassword());

    boolean isT = userService.updateUser(user);
    if (!isT) {
      return RestResponse.failure("重置密码失败");
    }

    return RestResponse.success(pwdDto);
  }

  /**
   * 重置密码校验
   */
  private User resetPwdValid(UserThirdDto userThirdDto) {

    ValidationUtils.restResponseValidate(userThirdDto, UserThirdDto.ResetPwd.class);
    companyRemoteService.companyValid(userThirdDto.getCompanyId());

    User user = userService.getUserByUserId(userThirdDto.getUserId());
    if (user == null) {
      throw new BusinessException("用户id不存在");
    }

    if (UserStatusEnum.DISABLED.getFlag() == user.getStatus()) {
      throw new BusinessException("用户已停用");
    }

    if (!user.getCompanyId().equals(userThirdDto.getCompanyId())) {
      throw new BusinessException("用户与企业id不匹配");
    }

    return user;
  }

  /**
   * 修改密码
   */
  @Override
  public RestResponse updatePwd(UserThirdDto userThirdDto) {

    User user = updatePwdValid(userThirdDto);

    user.setPassword(userThirdDto.getPassword());

    if (!userService.updateUser(user)) {
      return RestResponse.failure("修改密码失败");
    }

    return RestResponse.success();
  }

  /**
   * 修改密码校验
   */
  private User updatePwdValid(UserThirdDto userThirdDto) {

    ValidationUtils.restResponseValidate(userThirdDto, UserThirdDto.UpdatePwd.class);
    companyRemoteService.companyValid(userThirdDto.getCompanyId());

    User user = userService.getUserByAccount(userThirdDto.getAccount());
    if (user == null) {
      throw new BusinessException("账号不存在");
    }

    if (!user.getCompanyId().equals(userThirdDto.getCompanyId())) {
      throw new BusinessException("用户与企业id不匹配");
    }

    return user;
  }

  /**
   * 查询用户角色列表
   */
  @Override
  public RestResponse<UserRoleDto> getUserRoleByAccount(UserThirdDto userThirdDto) {
    log.info("查询用户角色列表 入参:{}", userThirdDto);
    User user = getUserRoleByAccountValid(userThirdDto);

    RoleDto roleDto = new RoleDto();
    roleDto.setStatus(RoleStatusEnum.ENABLED.getFlag());
    roleDto.setCompanyId(userThirdDto.getCompanyId());
    List<Role> roles = roleService.listRole(roleDto);

    UserRole userRole = new UserRole();
    userRole.setUserId(user.getUserId());
    log.info("查询用户角色列表 listUserRoleByUserId 入参:{}", userThirdDto);
    List<UserRole> userRoles = userRoleService.listUserRoleByUserId(userRole);

    UserRoleDto userRoleDto = new UserRoleDto();
    userRoleDto.setAccount(user.getAccount());
    userRoleDto.setRoles(roles);
    if (userRoles != null && !userRoles.isEmpty()) {
      userRoleDto.setRoleId(userRoles.get(0).getRoleId());
    }

    return RestResponse.success(userRoleDto);
  }

  /**
   * 查询用户角色列表参数校验
   */
  private User getUserRoleByAccountValid(UserThirdDto userThirdDto) {

    ValidationUtils.restResponseValidate(userThirdDto, UserThirdDto.GetUserRoleByAccount.class);
    companyRemoteService.companyValid(userThirdDto.getCompanyId());

    User user = userService.getUserByAccount(userThirdDto.getAccount());
    if (user == null) {
      throw new BusinessException("账号不存在");
    }

    if (!user.getCompanyId().equals(userThirdDto.getCompanyId())) {
      throw new BusinessException("用户与企业id不匹配");
    }

    return user;
  }
}
